package sistemadeproyectos;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Reader;
import java.util.Enumeration;
import java.util.HashMap;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.StyledEditorKit.ForegroundAction;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.rtf.RTFEditorKit;
import javax.swing.undo.*;

/*
 * Editor.java
 *
 * Created on 31-may-2012, 15:38:30
 */
/**
 *
 * @author giancarlo
 */
public class Editor extends javax.swing.JFrame {
    //Documento que contiene el texto y los atributos del JTextPane
    StyledDocument doc; 


    //Clases encargadas de deshacer y rehacer
    protected UndoAction undoAction = new UndoAction();
    protected RedoAction redoAction = new RedoAction();
    protected UndoManager undo = new UndoManager();
    protected MyUndoableEditListener UndoListener = new MyUndoableEditListener();

    /** Creates new form Editor */
    public Editor() {
        initComponents();
        //Inicializo el documento de nuestro JtextPane
        doc = textPane.getStyledDocument();
        String ruta = "";
        if(System.getProperty("os.name").substring(0,5).equals("Windo")){
            ruta = "\\src\\sistemadeproyectos\\images\\iconosEditor\\";
        }
        else if(System.getProperty("os.name").substring(0,5).equals("Linux")){
            ruta = "/src/sistemadeproyectos/images/iconosEditor/";
        }
    
        Nuevo_Button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "New.png", (Nuevo_Button.getWidth()/2), (Nuevo_Button.getHeight()/2)));
        load_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Cargar.png", (load_button.getWidth()/2), (load_button.getHeight()/2)));
        Save_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Save.png", (Save_button.getWidth()/2), (Save_button.getHeight()/2)));
        Deshacer_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Deshacer.png", (Deshacer_button.getWidth()/2), (Deshacer_button.getHeight()/2)));
        Rehacer_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Rehacer.png", (Rehacer_button.getWidth()/2), (Rehacer_button.getHeight()/2)));
        Copiar_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Copy.png", (Copiar_button.getWidth()/2), (Copiar_button.getHeight()/2)));
        Cortar_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Cut.png", (Cortar_button.getWidth()/2), (Cortar_button.getHeight()/2)));
        Pegar_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Paste.png", (Pegar_button.getWidth()/2), (Pegar_button.getHeight()/2)));
        Italic_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Italic.png", (Italic_button.getWidth()/2), (Italic_button.getHeight()/2)));
        Bold_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Bold.png", (Bold_button.getWidth()/2), (Bold_button.getHeight()/2)));
        Underline_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Underline.png", (Underline_button.getWidth()/2), (Underline_button.getHeight()/2)));
        LeftAlign_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Left.png", (LeftAlign_button.getWidth()/2), (LeftAlign_button.getHeight()/2)));
        Center_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Center.png", (Center_button.getWidth()/2), (Center_button.getHeight()/2)));
        RigthAlign_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Right.png", (RigthAlign_button.getWidth()/2), (RigthAlign_button.getHeight()/2)));
        JustAlign_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Justify.png", (JustAlign_button.getWidth()/2), (JustAlign_button.getHeight()/2)));
        Fuente_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Font.png", (Fuente_button.getWidth()/2), (Fuente_button.getHeight()/2)));
        Color_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "Text-color.png", (Color_button.getWidth()/2), (Color_button.getHeight()/2)));
        imagen_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "insertImage.png", (imagen_button.getWidth()/2), (imagen_button.getHeight()/2)));
        background_button.setIcon(ajustarImagen(System.getProperty("user.dir") 
                + ruta + "resalteTexto.png", (background_button.getWidth()/2), (background_button.getHeight()/2)));

        //Creamos el menu.
        JMenu styleMenu = createStyleMenu();
        JMenu EditMenu = createEditMenu();
        JMenu fileMenu = createFileMenu();
        JMenuBar mb = new JMenuBar();
        mb.add(fileMenu);
        mb.add(EditMenu);
        mb.add(styleMenu);
        setJMenuBar(mb);

        //ListarFuentes();
        
        /* Empezamos a registrar los cambios y asociamos los botones respectivos
           a las acciones de rehacer y deshacer. */
        undoAction.setUndo_button(Deshacer_button);
        redoAction.setRedo_Button(Rehacer_button);
        doc.addUndoableEditListener(UndoListener);
        textPane.setCaretPosition(0);
    }
   
    private ImageIcon ajustarImagen(String ico, int ancho, int alto) {
        ImageIcon tmpIconAux = new ImageIcon(ico);
        //Escalar Imagen
        ImageIcon tmpIcon = new ImageIcon(tmpIconAux.getImage().getScaledInstance(ancho, alto, Image.SCALE_DEFAULT));
        return tmpIcon;
    }
    
    //String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().
    //AvailableFontFamilyNames();
    
        /** 
     * Funcion para crear el menu de edicion.
     */
    protected JMenu createFileMenu() {
        JMenu menu = new JMenu("Archivo");

        JMenuItem nuevo = new JMenuItem("Nuevo");
        nuevo.addActionListener(Nuevo_Button.getActionListeners()[0]);
        menu.add(nuevo);

        JMenuItem guardar = new JMenuItem("Guardar");
        guardar.addActionListener(Save_button.getActionListeners()[0]);
        menu.add(guardar);
        
        JMenuItem abrir = new JMenuItem("Abrir");
        abrir.addActionListener(load_button.getActionListeners()[0]);
        menu.add(abrir);
        
        return menu;
    }
    
    /** 
     * Funcion para crear el menu de edicion.
     */
    protected JMenu createEditMenu() {
        JMenu menu = new JMenu("Edit");

        JMenuItem copiar = new JMenuItem("Copiar");
        copiar.setAction(new StyledEditorKit.CopyAction());
        menu.add(copiar);

        JMenuItem cortar = new JMenuItem("Cortar");
        cortar.setAction(new StyledEditorKit.CutAction());
        menu.add(cortar);
        
        JMenuItem pegar = new JMenuItem("Pegar");
        pegar.setAction(new StyledEditorKit.PasteAction());
        menu.add(pegar);
        
        menu.addSeparator();

        menu.add(undoAction);

        menu.add(redoAction);

        return menu;
    }
    
    /** 
     * Funcion para crear el menu de alineamiento.
     */
    protected JMenu createStyleMenu() {
        JMenu menu = new JMenu("Formato");

        JMenuItem fuente = new JMenuItem("Fuente");
        fuente.addActionListener(Fuente_button.getActionListeners()[0]);
        menu.add(fuente);

        JMenuItem color = new JMenuItem("Color de Texto");
        color.addActionListener(Color_button.getActionListeners()[0]);
        menu.add(color);
                
        menu.addSeparator();
        
        JMenuItem negrita = new JMenuItem("Negrita");
        negrita.setAction(new StyledEditorKit.BoldAction());
        menu.add(negrita);

        JMenuItem cursiva = new JMenuItem("Cursiva");
        cursiva.setAction(new StyledEditorKit.ItalicAction());
        menu.add(cursiva);
        
        JMenuItem subrayada = new JMenuItem("Subrayada");
        subrayada.setAction(new StyledEditorKit.UnderlineAction());
        menu.add(subrayada);
        
        menu.addSeparator();
        
        menu.add(new StyledEditorKit.AlignmentAction("Texto a Izquierda", 
                                            StyleConstants.ALIGN_LEFT));        
        menu.add(new StyledEditorKit.AlignmentAction("Texto Centrado", 
                                            StyleConstants.ALIGN_CENTER));
        menu.add(new StyledEditorKit.AlignmentAction("Texto a Derecha", 
                                            StyleConstants.ALIGN_RIGHT));
        menu.add(new StyledEditorKit.AlignmentAction("Texto Justificado", 
                                            StyleConstants.ALIGN_JUSTIFIED));

        return menu;
    }
        
    //Clase This one listens for edits that can be undone.
    protected class MyUndoableEditListener
                    implements UndoableEditListener {
        public void undoableEditHappened(UndoableEditEvent e) {
            //Recuerda la edicion de texto y actualiza los menus.
            undo.addEdit(e.getEdit());
            undoAction.updateUndoState();
            redoAction.updateRedoState();
        }
    }
    
    class UndoAction extends AbstractAction {
        JButton Undo_button;
        
        public UndoAction() {
            super("Undo");
            setEnabled(false);
        }

        public void setUndo_button(JButton Deshacer) {
            this.Undo_button = Deshacer;
            updateUndoState();
        }
        
        public void actionPerformed(ActionEvent e) {
            try {
                undo.undo();
            } catch (CannotUndoException ex) {
                System.out.println("Unable to undo: " + ex);
                ex.printStackTrace();
            }
            updateUndoState();
            redoAction.updateRedoState();
        }

        protected void updateUndoState() {
            if (undo.canUndo()) {
                setEnabled(true);
                (this.Undo_button).setEnabled(true);
                putValue(Action.NAME, undo.getUndoPresentationName());
            } else {
                setEnabled(false);
                (this.Undo_button).setEnabled(false);
                putValue(Action.NAME, "Undo");
            }
        }
    }

    class RedoAction extends AbstractAction {
        JButton Redo_button;
        
        public RedoAction() {
            super("Redo");
            setEnabled(false);
        }

        public void setRedo_Button(JButton Rehacer) {
            this.Redo_button = Rehacer;
            updateRedoState();
        }
        
        public void actionPerformed(ActionEvent e) {
            try {
                undo.redo();
            } catch (CannotRedoException ex) {
                System.out.println("Unable to redo: " + ex);
                ex.printStackTrace();
            }
            updateRedoState();
            undoAction.updateUndoState();
        }

        protected void updateRedoState() {
            if (undo.canRedo()) {
                setEnabled(true);
                (this.Redo_button).setEnabled(true);
                putValue(Action.NAME, undo.getRedoPresentationName());
            } else {
                setEnabled(false);
                (this.Redo_button).setEnabled(false);
                putValue(Action.NAME, "Redo");
            }
        }
    }
        
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        textPane = new javax.swing.JTextPane();
        Color_button = new javax.swing.JButton();
        Save_button = new javax.swing.JButton();
        Fuente_button = new javax.swing.JButton();
        load_button = new javax.swing.JButton();
        Deshacer_button = new javax.swing.JButton();
        Rehacer_button = new javax.swing.JButton();
        Copiar_button = new javax.swing.JButton();
        Pegar_button = new javax.swing.JButton();
        Cortar_button = new javax.swing.JButton();
        Underline_button = new javax.swing.JButton();
        Center_button = new javax.swing.JButton();
        LeftAlign_button = new javax.swing.JButton();
        RigthAlign_button = new javax.swing.JButton();
        Nuevo_Button = new javax.swing.JButton();
        Bold_button = new javax.swing.JButton();
        Italic_button = new javax.swing.JButton();
        JustAlign_button = new javax.swing.JButton();
        imagen_button = new javax.swing.JButton();
        background_button = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(sistemadeproyectos.SistemadeproyectosApp.class).getContext().getResourceMap(Editor.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        textPane.setName("textPane"); // NOI18N
        jScrollPane2.setViewportView(textPane);

        Color_button.setToolTipText(resourceMap.getString("Color_button.toolTipText")); // NOI18N
        Color_button.setName("Color_button"); // NOI18N
        Color_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Color_buttonActionPerformed(evt);
            }
        });

        Save_button.setToolTipText(resourceMap.getString("Save_button.toolTipText")); // NOI18N
        Save_button.setName("Save_button"); // NOI18N
        Save_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Save_buttonActionPerformed(evt);
            }
        });

        Fuente_button.setToolTipText(resourceMap.getString("Fuente_button.toolTipText")); // NOI18N
        Fuente_button.setName("Fuente_button"); // NOI18N
        Fuente_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Fuente_buttonActionPerformed(evt);
            }
        });

        load_button.setToolTipText(resourceMap.getString("load_button.toolTipText")); // NOI18N
        load_button.setName("load_button"); // NOI18N
        load_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                load_buttonActionPerformed(evt);
            }
        });

        Deshacer_button.setToolTipText(resourceMap.getString("Deshacer_button.toolTipText")); // NOI18N
        Deshacer_button.setEnabled(false);
        Deshacer_button.setName("Deshacer_button"); // NOI18N
        Deshacer_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Deshacer_buttonActionPerformed(evt);
            }
        });

        Rehacer_button.setToolTipText(resourceMap.getString("Rehacer_button.toolTipText")); // NOI18N
        Rehacer_button.setEnabled(false);
        Rehacer_button.setName("Rehacer_button"); // NOI18N
        Rehacer_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Rehacer_buttonActionPerformed(evt);
            }
        });

        Copiar_button.setToolTipText(resourceMap.getString("Copiar_button.toolTipText")); // NOI18N
        Copiar_button.setName("Copiar_button"); // NOI18N
        Copiar_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Copiar_buttonActionPerformed(evt);
            }
        });

        Pegar_button.setToolTipText(resourceMap.getString("Pegar_button.toolTipText")); // NOI18N
        Pegar_button.setName("Pegar_button"); // NOI18N
        Pegar_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Pegar_buttonActionPerformed(evt);
            }
        });

        Cortar_button.setToolTipText(resourceMap.getString("Cortar_button.toolTipText")); // NOI18N
        Cortar_button.setName("Cortar_button"); // NOI18N
        Cortar_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Cortar_buttonActionPerformed(evt);
            }
        });

        Underline_button.setToolTipText(resourceMap.getString("Underline_button.toolTipText")); // NOI18N
        Underline_button.setName("Underline_button"); // NOI18N
        Underline_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Underline_buttonActionPerformed(evt);
            }
        });

        Center_button.setText(resourceMap.getString("Center_button.text")); // NOI18N
        Center_button.setToolTipText(resourceMap.getString("Center_button.toolTipText")); // NOI18N
        Center_button.setName("Center_button"); // NOI18N
        Center_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Center_buttonActionPerformed(evt);
            }
        });

        LeftAlign_button.setText(resourceMap.getString("LeftAlign_button.text")); // NOI18N
        LeftAlign_button.setToolTipText(resourceMap.getString("LeftAlign_button.toolTipText")); // NOI18N
        LeftAlign_button.setName("LeftAlign_button"); // NOI18N
        LeftAlign_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LeftAlign_buttonActionPerformed(evt);
            }
        });

        RigthAlign_button.setText(resourceMap.getString("RigthAlign_button.text")); // NOI18N
        RigthAlign_button.setToolTipText(resourceMap.getString("RigthAlign_button.toolTipText")); // NOI18N
        RigthAlign_button.setName("RigthAlign_button"); // NOI18N
        RigthAlign_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RigthAlign_buttonActionPerformed(evt);
            }
        });

        Nuevo_Button.setToolTipText(resourceMap.getString("Nuevo_Button.toolTipText")); // NOI18N
        Nuevo_Button.setName("Nuevo_Button"); // NOI18N
        Nuevo_Button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Nuevo_ButtonActionPerformed(evt);
            }
        });

        Bold_button.setText(resourceMap.getString("Bold_button.text")); // NOI18N
        Bold_button.setToolTipText(resourceMap.getString("Bold_button.toolTipText")); // NOI18N
        Bold_button.setName("Bold_button"); // NOI18N
        Bold_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Bold_buttonActionPerformed(evt);
            }
        });

        Italic_button.setToolTipText(resourceMap.getString("Italic_button.toolTipText")); // NOI18N
        Italic_button.setName("Italic_button"); // NOI18N
        Italic_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Italic_buttonActionPerformed(evt);
            }
        });

        JustAlign_button.setToolTipText(resourceMap.getString("JustAlign_button.toolTipText")); // NOI18N
        JustAlign_button.setName("JustAlign_button"); // NOI18N
        JustAlign_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JustAlign_buttonActionPerformed(evt);
            }
        });

        imagen_button.setToolTipText(resourceMap.getString("imagen_button.toolTipText")); // NOI18N
        imagen_button.setName("imagen_button"); // NOI18N
        imagen_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                imagen_buttonActionPerformed(evt);
            }
        });

        background_button.setToolTipText(resourceMap.getString("background_button.toolTipText")); // NOI18N
        background_button.setName("background_button"); // NOI18N
        background_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                background_buttonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 1079, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(Nuevo_Button, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(load_button, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Save_button, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(23, 23, 23)
                        .addComponent(Deshacer_button, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Rehacer_button, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(Copiar_button, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Pegar_button, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Cortar_button, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31)
                        .addComponent(LeftAlign_button, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Center_button, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6)
                        .addComponent(RigthAlign_button, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(JustAlign_button, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(41, 41, 41)
                        .addComponent(Underline_button, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Bold_button, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Italic_button, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                        .addComponent(background_button, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(imagen_button, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Fuente_button, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Color_button, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(Underline_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(Rehacer_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(Deshacer_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(Save_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(JustAlign_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(Center_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(RigthAlign_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(load_button, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                        .addComponent(Nuevo_Button, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE))
                    .addComponent(Copiar_button, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(Pegar_button, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(Cortar_button, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(LeftAlign_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(imagen_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(Fuente_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(background_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(Bold_button, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(Italic_button, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                    .addComponent(Color_button, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /** 
     * Si se pulso el boton de guardar, se despliega un menu de colores para
     * cambia el color del texto.
     * OJO NO MOSTRAMOS EN EL MENU EL COLOR ACTUAL DEL TEXTO
     */
    private void Color_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Color_buttonActionPerformed
        AttributeSet texto = textPane.getCharacterAttributes();
        Color newColor = JColorChooser.showDialog(this, "Escoger color de linea", doc.getForeground(texto));
        if (newColor != null) 
        {
         new StyledEditorKit.ForegroundAction("Color", newColor).actionPerformed(evt);
        }
    }//GEN-LAST:event_Color_buttonActionPerformed

    /** 
     * Si se pulso el boton de guardar, le preguntamos al usuario por el nombre
     * del archivo que va a contener el texto guardado de nuestro editor
     * el formato con que se guarda el archivo es "prod".
     */
    private void Save_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Save_buttonActionPerformed
        JFileChooser fileChooser = new JFileChooser();   
        
        int result = fileChooser.showSaveDialog(null);
        if (result == JFileChooser.APPROVE_OPTION )
        {
          String loc_arch = (fileChooser.getSelectedFile()).getPath() + ".prod";      
          File arch_texto = new File(loc_arch);
          try {
        
              ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream(arch_texto));
              oos.writeObject (doc);
              oos.flush();
              oos.close();
                        
              JOptionPane.showMessageDialog(this, "Se guardo con exito", 
                        "Guardar", JOptionPane.INFORMATION_MESSAGE);
            } catch (FileNotFoundException e) {
                   JOptionPane.showMessageDialog(this, "Error al crear el archivo: "+ e.getMessage(), 
                        "Error al Guardar", JOptionPane.ERROR_MESSAGE);
            } catch (IOException e1){
                   JOptionPane.showMessageDialog(this, "Error al guardar el archivo: "+ e1.getMessage(), 
                        "Error al Guardar", JOptionPane.ERROR_MESSAGE);
            }       
        }
    }//GEN-LAST:event_Save_buttonActionPerformed

    /** 
     * Si se pulso el boton de fuentes, , se despliega un menu de fuentes para
     * cambiar la fuente del texto.
     * OJO HAY PROBLEMAS CUANDO SE QUIERE CAMBIAR EL ESTILO DE NEGRITAS O 
     * CURSIVAS A NORMAL NO CHEQUEAMOS EL ESTADO DEL TEXTO.
     */
    private void Fuente_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Fuente_buttonActionPerformed
        Fuente ventanaFuente = new Fuente(this, true);
        ventanaFuente.setVisible(true);
        if (ventanaFuente.fuenteEntregada != null){
            String fuente = (ventanaFuente.fuenteEntregada).getName();
            int tam = (ventanaFuente.fuenteEntregada).getSize();
            int style = (ventanaFuente.fuenteEntregada).getStyle();
            
            new StyledEditorKit.FontFamilyAction("fuente", 
                    fuente).actionPerformed(evt);
            new StyledEditorKit.FontSizeAction("fuente_size", tam).actionPerformed(evt);
        
            AttributeSet caracteristicas = textPane.getCharacterAttributes();
            
            boolean negrita = StyleConstants.isBold(caracteristicas);
            boolean cursiva = StyleConstants.isItalic(caracteristicas);
            
            if (style == Font.PLAIN) {
                if (negrita == true) {
                    new StyledEditorKit.BoldAction().actionPerformed(evt);
                }
                if (cursiva == true) {
                    new StyledEditorKit.ItalicAction().actionPerformed(evt); 
                }
            }
            if (style == Font.BOLD)               
            { 
                if (negrita == false) {
                    new StyledEditorKit.BoldAction().actionPerformed(evt);
                }
                if (cursiva == true) {
                    new StyledEditorKit.ItalicAction().actionPerformed(evt); 
                }
            }
            else if (style == Font.ITALIC)               
            {
                if (negrita == true) {
                    new StyledEditorKit.BoldAction().actionPerformed(evt);
                }
                if (cursiva == false) {
                    new StyledEditorKit.ItalicAction().actionPerformed(evt); 
                }
            }
            else if (style == (Font.BOLD+Font.ITALIC))
            { 
                if (negrita == false) {
                    new StyledEditorKit.BoldAction().actionPerformed(evt);
                }
                if (cursiva == false) {
                    new StyledEditorKit.ItalicAction().actionPerformed(evt); 
                }
            }
        }        
    }//GEN-LAST:event_Fuente_buttonActionPerformed

    /** 
     * Si se pulso el boton de cargar, le preguntamos al usuario por el nombre
     * del archivo que se va a cargar en el editor, solo se soporta el formato 
     * con que se guardan los archivos de este editor "prod".
     */
    private void load_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_load_buttonActionPerformed
        JFileChooser fileChooser = new JFileChooser();   
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivos soportados "
                + "Prueba Open Document: prod", "prod");
        
        fileChooser.setFileFilter(filter);
        fileChooser.setAcceptAllFileFilterUsed(false);
        int result = fileChooser.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION )
        {
            try {
                /*Actualizo la clase undo y el UndoAction y Redo Action 
                 * para que se percaten que la clase undo no puede ni rehacer ni deshacer*/
                undo.discardAllEdits();
                undoAction.setUndo_button(Deshacer_button);
                redoAction.setRedo_Button(Rehacer_button);
                
                /*Asigno al documento del textPanel el nuevo documento y vuelvo
                 a agregarle el escuchador de ediciones UndoListener*/
                ObjectInputStream ois = new ObjectInputStream (new FileInputStream(fileChooser.getSelectedFile()));
                doc = (StyledDocument)ois.readObject();
                doc.addUndoableEditListener(UndoListener);
                ois.close();
                textPane.setStyledDocument (doc);
                validate();
                
            } catch (FileNotFoundException e) {
                   JOptionPane.showMessageDialog(this, "Error al abrrir el archivo: "+ e.getMessage(), 
                        "Error en Carga", JOptionPane.ERROR_MESSAGE);
            } catch (IOException e1){
                   JOptionPane.showMessageDialog(this, "Error al leer el archivo: "+ e1.getMessage(), 
                        "Error en Carga", JOptionPane.ERROR_MESSAGE);
            } catch (ClassNotFoundException e3){
                   JOptionPane.showMessageDialog(this, "Parece que el archivo esta corrupto: "+ e3.getMessage(), 
                        "Error en carga", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_load_buttonActionPerformed

    private void Deshacer_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Deshacer_buttonActionPerformed
        (this.undoAction).actionPerformed(evt);
    }//GEN-LAST:event_Deshacer_buttonActionPerformed

    private void Rehacer_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Rehacer_buttonActionPerformed
        (this.redoAction).actionPerformed(evt);
    }//GEN-LAST:event_Rehacer_buttonActionPerformed

    private void Copiar_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Copiar_buttonActionPerformed
         new StyledEditorKit.CopyAction().actionPerformed(evt);
    }//GEN-LAST:event_Copiar_buttonActionPerformed

    private void Pegar_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Pegar_buttonActionPerformed
        new StyledEditorKit.PasteAction().actionPerformed(evt);
    }//GEN-LAST:event_Pegar_buttonActionPerformed

    private void Cortar_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Cortar_buttonActionPerformed
        new StyledEditorKit.CutAction().actionPerformed(evt);
    }//GEN-LAST:event_Cortar_buttonActionPerformed

    private void Underline_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Underline_buttonActionPerformed
        new StyledEditorKit.UnderlineAction().actionPerformed(evt);
    }//GEN-LAST:event_Underline_buttonActionPerformed

    private void LeftAlign_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LeftAlign_buttonActionPerformed
        new StyledEditorKit.AlignmentAction("Izquierda", StyleConstants.ALIGN_LEFT).actionPerformed(evt);
    }//GEN-LAST:event_LeftAlign_buttonActionPerformed

    private void Center_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Center_buttonActionPerformed
        new StyledEditorKit.AlignmentAction("Centro", StyleConstants.ALIGN_CENTER).actionPerformed(evt);
    }//GEN-LAST:event_Center_buttonActionPerformed

    private void RigthAlign_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RigthAlign_buttonActionPerformed
        new StyledEditorKit.AlignmentAction("Derecho", StyleConstants.ALIGN_RIGHT).actionPerformed(evt);
    }//GEN-LAST:event_RigthAlign_buttonActionPerformed

    private void Bold_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Bold_buttonActionPerformed
        new StyledEditorKit.BoldAction().actionPerformed(evt);
    }//GEN-LAST:event_Bold_buttonActionPerformed

    private void Italic_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Italic_buttonActionPerformed
        new StyledEditorKit.ItalicAction().actionPerformed(evt);        
    }//GEN-LAST:event_Italic_buttonActionPerformed

    private void JustAlign_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JustAlign_buttonActionPerformed
        new StyledEditorKit.AlignmentAction("Justificado", StyleConstants.ALIGN_JUSTIFIED).actionPerformed(evt);
    }//GEN-LAST:event_JustAlign_buttonActionPerformed

    private void Nuevo_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Nuevo_ButtonActionPerformed
        TipoTexto texto = new TipoTexto(this, true);
        texto.setVisible(true);
        if (texto.aceptar == true) {
            try {
                /*Actualizo la clase undo y el UndoAction y Redo Action 
                 * para que se percaten que la clase undo no puede ni rehacer ni deshacer*/
                undo.discardAllEdits();
                undoAction.setUndo_button(Deshacer_button);
                redoAction.setRedo_Button(Rehacer_button);

                /*Asigno al documento del textPanel el nuevo documento y vuelvo
                 a agregarle el escuchador de ediciones UndoListener*/
                ObjectInputStream ois = new ObjectInputStream (texto.documento);
                doc = (StyledDocument)ois.readObject();
                doc.addUndoableEditListener(UndoListener);
                ois.close();
                textPane.setStyledDocument (doc);
                validate();

            } catch (FileNotFoundException e) {
                   JOptionPane.showMessageDialog(this, "Error al abrrir el archivo: "+ e.getMessage(), 
                        "Error en Carga", JOptionPane.ERROR_MESSAGE);
            } catch (ClassNotFoundException e2){
                   JOptionPane.showMessageDialog(this, "Hubo una corrupcion en el archivo: "+ e2.getMessage(), 
                        "Error en Carga", JOptionPane.ERROR_MESSAGE);
            } catch (IOException e1){
                   JOptionPane.showMessageDialog(this, "Error al leer el archivo: "+ e1.getMessage(), 
                        "Error en Carga", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_Nuevo_ButtonActionPerformed

    private void imagen_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_imagen_buttonActionPerformed
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivos soportados "
                + "bmp, jpeg, gif", "jpeg","bmp","jpg","gif");
        
        chooser.setFileFilter(filter);
        chooser.setAcceptAllFileFilterUsed(false);
        int status = chooser.showOpenDialog(this);
        if (status == JFileChooser.APPROVE_OPTION) {
            File file = chooser.getSelectedFile();
            Icon icon = new ImageIcon (file.getAbsolutePath());
            textPane.insertIcon (icon);
        }
    }//GEN-LAST:event_imagen_buttonActionPerformed

    private void background_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_background_buttonActionPerformed
        Style resalte = textPane.getLogicalStyle();        
        Color newColor = JColorChooser.showDialog(this, "Escoger color de linea", doc.getBackground(resalte));
        if (newColor != null) 
        {   
            StyleConstants.setBackground(resalte, newColor);
            int lenght = textPane.getSelectionEnd() - textPane.getSelectionStart();
            doc.setLogicalStyle(textPane.getSelectionStart(), resalte);
            doc.setCharacterAttributes(textPane.getSelectionStart(), lenght, resalte, false);
        }    
    }//GEN-LAST:event_background_buttonActionPerformed
  
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Editor().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Bold_button;
    private javax.swing.JButton Center_button;
    private javax.swing.JButton Color_button;
    private javax.swing.JButton Copiar_button;
    private javax.swing.JButton Cortar_button;
    private javax.swing.JButton Deshacer_button;
    private javax.swing.JButton Fuente_button;
    private javax.swing.JButton Italic_button;
    private javax.swing.JButton JustAlign_button;
    private javax.swing.JButton LeftAlign_button;
    private javax.swing.JButton Nuevo_Button;
    private javax.swing.JButton Pegar_button;
    private javax.swing.JButton Rehacer_button;
    private javax.swing.JButton RigthAlign_button;
    private javax.swing.JButton Save_button;
    private javax.swing.JButton Underline_button;
    private javax.swing.JButton background_button;
    private javax.swing.JButton imagen_button;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton load_button;
    private javax.swing.JTextPane textPane;
    // End of variables declaration//GEN-END:variables
}
